<?php
/***********************************************************************
 * @package     IvanEngine
 * @subpackage  Core
 * @author      Ivan <ivanzx@msn.com>
 * @created     2010-06-05
 ***********************************************************************/
if(defined("IVANENGINE_CORE_STL_TREE"))
    die("Redefinition macro in :".__FILE__."(".__LINE__.")");
define("IVANENGINE_CORE_STL_TREE", true);

require_once (dirname(__FILE__).'/Map.php');

class CTree extends CObject implements Iterator
{
    protected $m_childMap   = null;
    protected $m_parent     = null;
    public function __construct($name) 
    {
        parent::__construct($name);
        $this->m_childMap   = new CMap();
    }

    public function __destruct()
    {
        unset($this->m_childMap);
        parent::__destruct();
    }
    
    public function SetParent(CTree & $parent)
    {
        $this->m_parent = $parent;
    }
    
    public function & GetParent()
    {
        return $this->m_parent;
    }
    
    public function AddChild(CTree & $child)
    {
        if( !$this->m_childMap->HasKey($child->GetName()) )
        {
            $child->SetParent($this);
            $this->m_childMap->Add($child->GetName(), $child);
        }
    }
    
    public function & GetChild($where, $recursive = false)
    {
        $result = $this->m_childMap->Get($where);
        if( $recursive == false ){
            return $result;
        }else{
            if( !$result )
            {
                $it = $this->m_childMap->Begin();
                for( ; !$it->IsEnd(); $it->Next() )
                {
                    $result = $it->Value()->GetChild($where, $recursive);
                    if( $result )
                    {
                        return $result;
                    }
                }
            }
        }
        return $result;
    }
    
    public function & GetChilds()
    {
        return $this->m_childMap;
    }
    
    public function GetChildCount()
    {
        return $this->m_childMap->Size();
    }
    
    public function RemoveChild($name)
    {
        $this->m_childMap->Remove($name);
    }
    
    public function RemoveAllChild()
    {
        foreach( $this->m_childMap as $child ){
            $child->RemoveAllChild();
        }
        $this->m_childMap->Clear();
    }
    
    
    public function rewind() 
    { 
        $this->m_childMap->rewind(); 
    }
    
    public function current() 
    { 
        return $this->m_childMap->current(); 
    }
    
    public function key() 
    { 
        return $this->m_childMap->key(); 
    }
    
    public function next() 
    { 
        return $this->m_childMap->next(); 
    }
    
    public function valid() 
    { 
        return $this->m_childMap->valid(); 
    }
}
?>
